/**
 * read json file
 */
const fs = require('fs');
const path = require('path');
const logic = require('logic-helper/server/koa/index.js')
const parser = require('../utils/parser.js')
const eventBus = require('ws-event-bus').default
const jsonDirFile = require("json_dir_file")

const PWD = path.dirname(process.cwd()) + '/task-stream'
const CWD = process.cwd()
const isDev = PWD === CWD;
console.log('isDev', isDev, PWD)
function objType(path) {
    return fs.statSync(path).isFile() ? 'file' : 'dir'
}

function whatIsThis(path) {
    if (fs.existsSync(path)) {
        return objType(path)
    }
}
// 判断两个对象是否相等
function deepEquals(source, comparison) {
    if (source === comparison) {
        return true;
    } else if ((source == null && comparison != null) || (source != null && comparison == null)) {
        return false
    } else if (Number.isNaN(source) && Number.isNaN(comparison)) {
        return true
    }
    var sourceType = getObjType(source)
    var comparisonType = getObjType(comparison)

    if (sourceType !== comparisonType) {
        return false;
    }

    const sourceKeys = Object.keys(source);
    const comparisonKeys = Object.keys({
        ...source,
        ...comparison
    });
    if (sourceKeys.length === 0 && comparisonKeys.length === 0) {
        return true;
    }
    if (sourceKeys.length !== comparisonKeys.length) {
        return false;
    }
    // source 与 sourceKeys 有相同key因为长度相等
    //默认相等
    var flag = true;
    sourceKeys.forEach(key => {
        if (!deepEquals(source[key], comparison[key])) {
            // 存在一个不相等的情况，说明2对象不相等
            flag = false
        }
    })
    return flag
}

function readAllJsonFileFromPath(filePath, callback) {
    fs.readdir(filePath, function (err, files) {
        if (err) {
            console.log(err);
            return;
        }
        var jsFiles = files.filter(function (file) {
            return file.split('.').pop() === 'json';
        });
        var jsonFiles = [];
        jsFiles.forEach(function (file) {
            var jsonFile = path.join(filePath, file);
            jsonFiles.push({
                path: jsonFile,
                name: file.replace('.json', '')
            });
        });
        callback && callback(jsonFiles);
    });
}

function readJsonFileFromPath(path, callback) {
    fs.readFile(path, function (err, data) {
        if (err) {
            console.log(err);
            return;
        }
        callback && callback(data);
    });
}

const objectTypeMap = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
    "[object Symbol]": "symbol",
    "[object AsyncFunction]": "function",
};
const toString = Object.prototype.toString;
const getObjType = (obj) => {
    return objectTypeMap[toString.call(obj)];
};

function delAllJsFiles(path) {
    let files = fs.readdirSync(path);
    files.forEach(function (file) {
        let stat = fs.statSync(path + '/' + file);
        if (!stat.isDirectory()) {
            fs.unlinkSync(path + '/' + file);
        }
    });
}

function readFileSync(route) {
    return fs.readFileSync(path.resolve(__dirname, route), 'utf-8')
}

function getTemplateContent() {
    const con = readFileSync('./template.js')
    const startReg = /\/\*\s{0,}template_start\s{0,}\*\//;
    const endReg = /\/\*\s{0,}template_end\s{0,}\*\//;
    let start = con.match(startReg);
    let end = con.match(endReg);
    let startIdx = start.index;
    let endIdx = end.index;
    let startLen = start[0].length;
    let template = con.slice(startIdx + startLen, endIdx);
    return template;
}


exports.isDev = isDev
exports.whatIsThis = whatIsThis
exports.deepEquals = deepEquals
exports.readJsonFileFromPath = readJsonFileFromPath
exports.readAllJsonFileFromPath = readAllJsonFileFromPath
exports.getObjType = getObjType
exports.delAllJsFiles = delAllJsFiles
